//
//  PKTools.m
//  PDFKitTest
//
//  Created by Emo, on 2022/12/6.
//

#import "PKTools.h"

@interface PKTools ()

@end

@implementation PKTools


+ (instancetype)sharedInstance {
    static PKTools *tools = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[PKTools alloc] init];
    });
    return tools;
}

//获取当前控制器
+ (UIViewController *)getCurrentVC {
    UIWindow* window = [self getCurrentWindow];
    UIViewController* currentViewController = window.rootViewController;
    BOOL runLoopFind = YES;
    while (runLoopFind) {
        if (currentViewController.presentedViewController) {
            currentViewController = currentViewController.presentedViewController;
        } else {
            if ([currentViewController isKindOfClass:[UINavigationController class]]) {
                currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
            } else if ([currentViewController isKindOfClass:[UITabBarController class]]) {
                currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
            } else {
                break;
            }
        }
    }
    return currentViewController;
}

+ (UIWindow *)getCurrentWindow {
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in [windows reverseObjectEnumerator]) {
        if ([window isKindOfClass:[UIWindow class]] && window.windowLevel == UIWindowLevelNormal && CGRectEqualToRect(window.bounds, [UIScreen mainScreen].bounds)) {
            return window;
        }
    }
    return [UIApplication sharedApplication].keyWindow;
}

/**
 * 根据页数生成一张图片
 */
- (UIImage *)getUIImageFromPDFPage:(size_t)pageNumber documentRef:(CGPDFDocumentRef)document {
    CGPDFPageRef page = CGPDFDocumentGetPage(document, pageNumber);
    CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
    pageRect.origin = CGPointZero;
    pageRect.size.width = pageRect.size.width * 2;
    pageRect.size.height = pageRect.size.height * 2;
    
    //开启图片绘制上下文
    UIGraphicsBeginImageContext(pageRect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    //设置白色背景
    CGContextSetRGBFillColor(context, 1, 1, 1, 1);
    CGContextFillRect(context, pageRect);
    CGContextSaveGState(context);
    
    //进行翻转
    CGContextTranslateCTM(context, -pageRect.size.width/2, pageRect.size.height*1.5);
    CGContextScaleCTM(context, 2, -2);
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
    CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(page, kCGPDFMediaBox, pageRect, 0, true));
    CGContextDrawPDFPage(context, page);
    CGContextRestoreGState(context);
    UIImage *pdfImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return pdfImage;
}


- (void)shareFileWithTitle:(NSString *)title path:(NSString *)path {
    NSURL *url = [NSURL fileURLWithPath:path];
    CFURLRef ref = (__bridge CFURLRef)url;
    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(ref);
    CFRelease(ref);
    size_t pageCount = CGPDFDocumentGetNumberOfPages(pdf);
    UIImage *image = [UIImage imageNamed:@"aboutus_logo"];
    if (pageCount > 0) {
        image = [self getUIImageFromPDFPage:1 documentRef:pdf];
    }
    NSArray *items = @[url];
    dispatch_async(dispatch_get_main_queue(), ^{
        UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
        [[PKTools getCurrentVC] presentViewController:activity animated:YES completion:nil];
    });
}


/**
 * 保存图片到相册
 */
- (void)saveImageToPhoto:(UIImage *)image {
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
}

/**
 * 状态栏高度
 */
+ (CGFloat)don_statusBarHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIStatusBarManager *statusBarManager = windowScene.statusBarManager;
        return statusBarManager.statusBarFrame.size.height;
    } else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}

/**
 * 导航高度（44.0f）
 */
+ (CGFloat)don_navigationHeight {
    return 44.0f;
}


/**
 * 导航栏高度（状态栏高度 + 导航高度）
 */
+ (CGFloat)don_navigationBarHeight {
    return [self don_statusBarHeight] + [self don_navigationHeight];
}

/**
 * 底部安全高度
 */
+ (CGFloat)don_safeBottomHeight {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIWindow *window = windowScene.windows.firstObject;
        return window.safeAreaInsets.bottom;
    } else if (@available(iOS 11.0, *)) {
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        return window.safeAreaInsets.bottom;
    }
    return 0;
}

/**
 * 标签高度（49.0f）
 */
+ (CGFloat)don_tabHeight {
    return 49.0f;
}

/**
 * tabBar高度（底部安全高度 + 标签高度）
 */
+ (CGFloat)don_tabBarHeight {
    return [self don_safeBottomHeight] + [self don_tabHeight];
}

@end
